package com.servlet.file;

import com.domain.FileClass;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.cj.xdevapi.JsonArray;
import com.mysql.cj.xdevapi.JsonLiteral;
import com.mysql.cj.xdevapi.JsonParser;
import com.mysql.cj.xdevapi.JsonValue;
import com.service.FileService;
import com.service.impl.FileServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/fileSelectServlet")
public class FileSelectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        FileService service = new FileServiceImpl();

        ArrayList<FileClass> select = service.select();
        StringBuilder data = new StringBuilder();

        ObjectMapper mapper = new ObjectMapper();
        if(select.size() < 1) {
            response.getWriter().write("{\"status\":\"0\",\"message\":\"ok\",\"data\":[]}");
            return;
        }

        data.append("[");
        for (FileClass fileClass : select) {
            String s = mapper.writeValueAsString(fileClass);
            data.append(s);
            data.append(",");
        }
        data.deleteCharAt(data.length() - 1);
        data.append("]");

        String json = "{\"status\":\"0\",\"message\":\"ok\",\"data\":"+data.toString()+"}";
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
